package com.sunday.aomicaichang.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.MainActivity;
import com.sunday.member.SessionToken;
import com.sunday.member.entity.Member;
import com.sunday.member.http.MemberClient;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends BaseActivity {
    @Bind(R.id.edt_username)
    EditText edtUsername;
    @Bind(R.id.edt_password)
    EditText edtPassword;
    @Bind(R.id.btn_register)
    TextView btnRegister;
    @Bind(R.id.btn_forget_password)
    TextView btnForgetPassword;
    @Bind(R.id.btn_login)
    TextView btnLogin;
    @Bind(R.id.btn_wechat)
    TextView btnWechat;
    @Bind(R.id.see)
    TextView see;

    private String userName, userPwd;
    private UMShareAPI umShareAPI;
    private boolean isSee = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        mContext = this;
        umShareAPI = UMShareAPI.get(this);
        setThirdLoginSettings();
    }

    private void setThirdLoginSettings() {
        //每次登录都弹出授权页面，便于切换账号
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(LoginActivity.this).setShareConfig(config);
    }

    @OnClick({R.id.btn_login, R.id.btn_register, R.id.btn_forget_password, R.id.see,R.id.btn_wechat})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                userName = edtUsername.getText().toString().trim();
                userPwd = edtPassword.getText().toString().trim();
                if (TextUtils.isEmpty(userName)) {
                    ToastUtils.showToast(mContext, "请填写正确账号");
                    return;
                }
                if (TextUtils.isEmpty(userPwd)) {
                    ToastUtils.showToast(mContext, "请填写正确密码");
                    return;
                }
                submit();
                break;
            case R.id.btn_register:
                Intent intent = new Intent(mContext, RegisterOneActivity.class);
                startActivity(intent);
                break;
            case R.id.see:
                see.setSelected(!isSee);
                isSee = !isSee;
                if (isSee) {
                    edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }

                break;
            case R.id.btn_forget_password:
                if (TextUtils.isEmpty(edtUsername.getText().toString())) {
                    ToastUtils.showToast(mContext, "请输入电话号");
                    return;
                }
                if (edtUsername.getText().toString().length() != 11) {
                    ToastUtils.showToast(mContext, "请输入正确电话号");
                    return;
                }
                intent = new Intent(mContext, ForgetPasswordActivity.class);
                intent.putExtra("phone", edtUsername.getText().toString());
                startActivity(intent);
                break;
            case R.id.btn_wechat:
                umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
                break;
        }
    }

    private void submit() {
        showLoadingDialog(0);
        Call<ResultDO<Member>> call = MemberClient.getApiAdapter().login(userName, userPwd, 1);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Member> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                    BaseApp.getInstance().setMember(resultDO.getResult());
                    SessionToken.accountId = String.valueOf(resultDO.getResult().getId());
                    SessionToken.token = resultDO.getResult().getToken();
                    ToastUtils.showToast(mContext, "登录成功");
                    intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private Context mContext;

    public void oauthLoginClick(View view) {
        String tag = (String) view.getTag();
        switch (tag) {
            case "1":
                umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
                break;
            case "2":
                umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, umAuthListener);
                break;
            case "3":
                umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, umAuthListener);
                break;
        }

    }

    private String token, logo, nickName, sex;
    private int type, sexType;
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA share_media, final int i, Map<String, String> map) {
            switch (share_media) {
                case WEIXIN:
                    token = map.get("openid");
                    logo = map.get("iconurl");
                    nickName = map.get("name");
                    sex = map.get("gender");
                    type = 1;
                    thirdLogin();
                    break;
                case QQ:
                    token = map.get("uid");
                    logo = map.get("iconurl");
                    nickName = map.get("name");
                    sex = map.get("gender");
                    type = 2;
                    thirdLogin();
                    break;
                case SINA:
                    token = map.get("uid");
                    logo = map.get("iconurl");
                    nickName = map.get("name");
                    sex = map.get("gender");
                    type = 3;
                    thirdLogin();
                    break;
            }
        }

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            ToastUtils.showToast(mContext, "授权失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            ToastUtils.showToast(mContext, "授权取消");
        }
    };


    private void thirdLogin() {
        showLoadingDialog(0);
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().loginWithThirdOne(token, type);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Member> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                    BaseApp.getInstance().setMember(resultDO.getResult());
                    SessionToken.accountId = String.valueOf(resultDO.getResult().getId());
                    SessionToken.token = resultDO.getResult().getToken();
                    intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                    Intent intent = new Intent(mContext, BindPhoneActivity.class);
                    intent.putExtra("type", type);
                    intent.putExtra("token", token);
                    intent.putExtra("logo", logo);
                    intent.putExtra("nickName", nickName);
                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }


}
